package cn.sytton.taffe.framework.security.user;

import cn.sytton.taffe.framework.security.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 用户AuthenticationProvider
 *
 * @author skyrock
 */
@Slf4j
@Component
public class UserAuthenticationProvider implements AuthenticationProvider, InitializingBean {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        LoginUser user = (LoginUser) authentication.getPrincipal();

        //验证
        additionalAuthenticationChecks(user, (UserAuthenticationToken)authentication);

        UserAuthenticationToken authenticationResult = new UserAuthenticationToken(user, authentication.getCredentials(), user.getAuthorities());

        authenticationResult.setDetails(authenticationResult.getDetails());

        return authenticationResult;
    }

    protected void additionalAuthenticationChecks(LoginUser loginUser, UserAuthenticationToken authentication) throws AuthenticationException {
        //
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UserAuthenticationToken.class.isAssignableFrom(authentication);
    }

    @Override
    public void afterPropertiesSet() {
        //
    }
}
